package com.addcn.caruimodule.bar;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;


import com.addcn.caruimodule.R;
import com.addcn.caruimodule.util.WindowUtil;

import java.util.ArrayList;
import java.util.List;

/*
 *ListView右側導航面板
 */
public class SideBar extends View {
    // 是否點選
    private boolean showBkg = false;
    // 監聽面板是否點選介面
    private OnTouchingLetterChangedListener onTouchingLetterChangedListener;
    //
    private List<String> b;
    private List<Float> indexY = new ArrayList<Float>();

    // 選擇的值
    int choose = -1;
    // 畫筆
    Paint paint = new Paint();
    private float SsingleHeight;
    private int totalHeight;
    private int defult = WindowUtil.dp2px(getContext(),20);
    private float mediuSize = 0.6f;
    private float mediuToastSize = 0.6f;
    private int startIndex = 0;
    private Vibrator vibrator;
    private Bitmap bitmap;
    private Paint mBitPaint;
    private int textSize = WindowUtil.sp2px(getContext(),12);
    private int checkTextColor = Color.parseColor("#FFFFFF");
    private int unCheckTextColor = Color.parseColor("#999999");
    private int textBackgroundColor = Color.parseColor("#3264FF");
    private int radios = WindowUtil.dp2px(getContext(),9);
    private int toastRight = WindowUtil.dp2px(getContext(),80);
    private int toastTextColor = Color.parseColor("#FFFFFF");
    private int toastTextSize = WindowUtil.sp2px(getContext(),20);
    private Drawable toastDrawable = getResources().getDrawable(R.drawable.ic_bar_bg);
    private boolean isToast = true;
    private boolean isVobrator = true;
    private float satrtIndex = -1;
    private float toastTextX = 0;
    private float toastTextY = 0;
    public SideBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context, attrs);
    }

    public SideBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    public SideBar(Context context) {
        super(context);
        initView(context, null);
    }

    private void initView(Context context, AttributeSet attrs) {
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomBrandbar);
            textSize = typedArray.getDimensionPixelSize(R.styleable.CustomBrandbar_bar_textSize, textSize);
            checkTextColor = typedArray.getColor(R.styleable.CustomBrandbar_bar_check_textColor, checkTextColor);
            unCheckTextColor = typedArray.getColor(R.styleable.CustomBrandbar_bar_uncheck_textColor, unCheckTextColor);
            textBackgroundColor = typedArray.getColor(R.styleable.CustomBrandbar_bar_backgroundColor, textBackgroundColor);
            toastRight = typedArray.getDimensionPixelSize(R.styleable.CustomBrandbar_bar_toast_right, toastRight);
            toastTextColor = typedArray.getColor(R.styleable.CustomBrandbar_bar_toast_textColor, toastTextColor);
            toastDrawable = typedArray.getDrawable(R.styleable.CustomBrandbar_bar_toast_background);
            if (toastDrawable == null) {
                toastDrawable = getResources().getDrawable(R.drawable.ic_bar_bg);
            }
            mediuSize = typedArray.getFloat(R.styleable.CustomBrandbar_bar_medium_textSize, mediuSize);
            mediuToastSize = typedArray.getFloat(R.styleable.CustomBrandbar_bar_toast_medium_textSize, mediuToastSize);
            toastTextSize = typedArray.getDimensionPixelSize(R.styleable.CustomBrandbar_bar_toast_textSize, toastTextSize);
            toastTextX = typedArray.getFloat(R.styleable.CustomBrandbar_bar_toast_x, toastTextX);
            toastTextY = typedArray.getFloat(R.styleable.CustomBrandbar_bar_toast_y, toastTextY);
            radios = typedArray.getDimensionPixelSize(R.styleable.CustomBrandbar_bar_radios, radios);
            isToast = typedArray.getBoolean(R.styleable.CustomBrandbar_bar_toast_show, isToast);
            isVobrator = typedArray.getBoolean(R.styleable.CustomBrandbar_bar_vibrator, isVobrator);
        }
        vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
        mBitPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBitPaint.setFilterBitmap(true);
        mBitPaint.setDither(true);
        bitmap = ((BitmapDrawable) toastDrawable).getBitmap();
    }

    /**
     * 重寫這個方法
     */
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 如果面板處於點選狀態就將面板的背景色繪製為灰色
        // 獲得Ｖｉｅｗ的高
        if (b == null) {
            return;
        }
        totalHeight = defult * b.size() > getHeight() ? getHeight() : defult * (b.size() + 1);
        startIndex = (getMeasuredHeight() - totalHeight) / 2 + defult / 2;
        // 計算得出每一個字型大概的高度
        if (b != null && !b.isEmpty()) {
            int singleHeight = WindowUtil.dp2px(getContext(),20);
            int a = b.size();
            float ZsingleHeight = singleHeight * a;
            SsingleHeight = (totalHeight - ZsingleHeight) / 2 + startIndex;
            for (int i = 0; i < a; i++) {
                // 設定鋸齒
                paint.setAntiAlias(true);
                // 設定字型大小
                paint.setTextSize(textSize);
                paint.setStrokeWidth(mediuSize);
                // 得到字型的X座標
                float xPos = WindowUtil.getScreenWidth(getContext()) - defult / 2 - paint.measureText(b.get(i)) / 2;
                // 得到字型的Y座標
                float yPos = SsingleHeight + singleHeight * i;
                if (i == 0) {
                    satrtIndex = yPos;
                }
                if (i == choose) {
                    // 繪製點選的字型的顏色為藍色
                    paint.setColor(checkTextColor);
                    paint.setFakeBoldText(true);
                    paint.setStrokeWidth(mediuSize);
                    Paint paint1 = new Paint();
                    paint1.setAntiAlias(true);
                    paint1.setColor(textBackgroundColor);
                    canvas.drawCircle(xPos + paint.measureText(b.get(i)) / 2, yPos - defult / 4, radios, paint1);

                    if (isToast) {
                        Paint paint2 = new Paint();
                        paint2.setAntiAlias(true);
                        paint2.setColor(toastTextColor);
                        paint2.setStrokeWidth(mediuToastSize);
                        paint2.setTextSize(toastTextSize);
                        canvas.drawBitmap(bitmap, xPos - toastRight, yPos - bitmap.getHeight() / 2 - defult / 4, mBitPaint);
                        canvas.drawText(b.get(i), xPos - toastRight + bitmap.getWidth() / 2 - paint2.measureText(b.get(i)) / 2+toastTextX, yPos+toastTextY, paint2);
                    }

                } else {
                    paint.setColor(unCheckTextColor);
                }
                // 將字型繪製到面板上
                indexY.add(yPos);
                canvas.drawText(b.get(i), xPos, yPos, paint);

                // 還原畫布
                paint.reset();
            }
        }
    }

    /**
     * 點選事件
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final float x = event.getX();
        if (!b.isEmpty()) {
            // 得到點選的狀態
            int singleHeight = WindowUtil.dp2px(getContext(),20) / 2;
            final int action = event.getAction();
            // 點選的Y座標
            final int c;
            final float y = event.getY() - satrtIndex;
            if (y < singleHeight && y >= -singleHeight) {
                c = 0;
            } else if (y < -singleHeight){
                // 得到當前的值
                c = 0;
                //return true;
            }else{
                c = (int) (y / (totalHeight) * b.size()) + 1;
            }
            final int oldChoose = choose;
            // 監聽
            final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener;
            // 根據點選的狀態不同做出不同的處理
            switch (action) {
                // 按下已經開始
                case MotionEvent.ACTION_DOWN:
                    // 將開關設定為true
                    showBkg = true;
                    if (oldChoose != c && listener != null) {
                        if (c > -1 && c < b.size()) {
                            // 噹噹前點選的值繫結監聽
                            // 這個監聽在本頁面中做的是介面。實際呼叫是在BrandListActivity中。也就是說我們呼叫這個介面會執行BrandListActivity的方法
                            if (x < WindowUtil.getScreenWidth(getContext()) && x > (WindowUtil.getScreenWidth(getContext()) - defult - paint.measureText(b.get(0)))) {
                                listener.onTouchingLetterChanged(b.get(c));
                                if (isVobrator) {
                                    vibrator.vibrate(30);
                                }
                                choose = c;
                                // 重新整理介面
                                invalidate();
                            }
                        }
                    }

                    break;
                // 鬆開為完成點選
                case MotionEvent.ACTION_MOVE:
                    if (oldChoose != c && listener != null) {
                        if (c > -1 && c < b.size()) {
                            if (x < WindowUtil.getScreenWidth(getContext()) && x > (WindowUtil.getScreenWidth(getContext()) - defult - paint.measureText(b.get(0)))) {
                                listener.onTouchingLetterChanged(b.get(c));
                                if (isVobrator) {
                                    vibrator.vibrate(10);
                                }
                                choose = c;
                                invalidate();
                            }
                        }
                    }
                    break;
                // 完成鬆開 還原資料 並重新整理介面
                case MotionEvent.ACTION_UP:
                    showBkg = false;
                    choose = -1;
                    invalidate();
                    break;
            }
        }
        if (!b.isEmpty() && x < WindowUtil.getScreenWidth(getContext()) && x > (WindowUtil.getScreenWidth(getContext()) - defult - paint.measureText(b.get(0)))) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    /**
     * 向外公開的方法
     *
     * @param onTouchingLetterChangedListener
     */
    public void setOnTouchingLetterChangedListener(
            OnTouchingLetterChangedListener onTouchingLetterChangedListener) {
        this.onTouchingLetterChangedListener = onTouchingLetterChangedListener;
    }

    /**
     * 介面
     *
     * @author coder
     */
    public interface OnTouchingLetterChangedListener {
        public void onTouchingLetterChanged(String s);
    }

    /**
     * 新增字母集合
     *
     * @param mList
     */
    public void setIndex(List<String> mList) {
        b = mList;
    }

    public void setMediuSize(float mediuSize) {
        this.mediuSize = mediuSize;
    }

    public void setToastTextSize(int toastTextSize) {
        this.toastTextSize = toastTextSize;
    }

    public void setMediuToastSize(float mediuToastSize) {
        this.mediuToastSize = mediuToastSize;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}
